<!--

This sample illustrates how to let the user choose a friend and then
send a private message to that friend.

-->
Select the friend to send the message to:
<div id='friendlist'>
</div>
<span style='color: grey' id='status'></span>

<script type='text/javascript'>
function setStatus(s) {
   debug.say(s);
   document.getElementById('status').innerHTML = s;
}

function init() {
   // load friends
   var req = opensocial.newDataRequest();

   var opt_params = {};
   opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 20;

   var idspec = opensocial.newIdSpec({ "userId":"VIEWER", "groupId":"FRIENDS" });
   req.add(req.newFetchPeopleRequest(idspec, opt_params), 'friends');
   req.send(onLoadFriends);
   setStatus("Loading friends... Please wait.");
}

function onLoadFriends(data) {
   if (data.hadError()) {
      setStatus("*** error: " + data.getErrorMessage());
      return;
   }

   var friends = data.get('friends').getData().asArray();
   var html = [ "<ul>" ];
   for (var i in friends) {
      html.push("<li><a href='javascript:void(0)' ");
      html.push("onclick='window.sendToFriend(\"");
      html.push(friends[i].getId());
      html.push("\")'>Send to ");
      html.push(friends[i].getDisplayName());
      html.push("</a></li>");
   }
   html.push("</ul>");
   document.getElementById('friendlist').innerHTML = html.join('');
   setStatus("Choose a friend to send a message to.");
}

// we have to put this function in the window because we are using it as a literal
// event handler on the link (sure, there are more elegant ways to do this, but
// since this is just an example, we're not focusing on Javascript beauty)
window.sendToFriend = function(opensocialID) {
   sendTheMessage(opensocialID, 
      "Test message", 
      "Hello! This is a <b>test</b>! " + 
            "Isn't <a href='http://www.orkut.com'>Orkut</a> <em>cool?</em>");
};

function sendTheMessage(to, title, body) {
   var params = {};
   params[opensocial.Message.Field.TITLE] = title;
   params[opensocial.Message.Field.BODY] = body;

   opensocial.requestSendMessage(to, 
      opensocial.newMessage(params),
      onMessageSent);

   setStatus("Message request sent. Waiting for confirmation...");
}

function onMessageSent(data) {
   setStatus(data.hadError() ? 
      "*** Error: " + data.getErrorMessage() : "Success.");
}

gadgets.util.registerOnLoadHandler(init);
</script>
